package main

import (
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/tebeka/selenium"
	"github.com/tebeka/selenium/chrome"
)

// This example scrapes the reviews shown on the home page of metalsucks.net.
func main() {
	//demo1()
	//demo3()
	seleniumGetUp()
}

//demo1 抓取 Go语言中文网 社区主题 — http://studygolang.com/topics
//https://www.flysnow.org/2018/01/20/golang-goquery-examples-selector.html
func demo1() {
	doc, err := goquery.NewDocument("http://studygolang.com/topics")
	if err != nil {
		log.Fatal(err)
	}
	//<dl class="topics dl-horizontal">
	doc.Find(".topics .topic").Each(func(i int, contentSelection *goquery.Selection) {
		title := contentSelection.Find(".title a").Text()
		num := contentSelection.Find(".pull-right a").Text()
		//<a href="/user/ZUIHAO1997" title="ZUIHAO1997" class="author"> </a>
		author := contentSelection.Find(".meta .author").Text()
		log.Println("第", i+1, "个帖子的标题：", title, " 评论数:", num, "作者：", author)
	})

	//https://studygolang.com/books

}

//demo2 Class选择器
func demo2() {
	html := `<body>

	<div id="div1">DIV1</div>
	<div class="name">DIV2</div>
	<span>SPAN</span>

</body>
`

	dom, err := goquery.NewDocumentFromReader(strings.NewReader(html))
	if err != nil {
		log.Fatalln(err)
	}

	dom.Find(".name").Each(func(i int, selection *goquery.Selection) {
		fmt.Println(selection.Text())
	})
}

//demo3 Class选择器
func demo3() {
	html := `<body>

	<div id="div1">DIV1</div>
	<div class="name">DIV2</div>
	<span>SPAN</span>
	<div class="footer garr-footer-publish-content">
	<button class="byte-btn byte-btn-primary byte-btn-size-default byte-btn-shape-square publish-content" type="button"><span>发布</span></button>
   </div>

</body>
`

	dom, err := goquery.NewDocumentFromReader(strings.NewReader(html))
	if err != nil {
		log.Fatalln(err)
	}

	dom.Find(".byte-btn.byte-btn-primary.byte-btn-size-default.byte-btn-shape-square.publish-content").Each(func(i int, selection *goquery.Selection) {
		fmt.Println(selection.Text())
	})
}

//seleniumGetUp keep good habit of getting up early
func seleniumGetUp() {

	//https://github.com/tebeka/selenium
	//https://pylist.com/t/1585314462
	var seleniumPath string = "D:\\local\\python3.6.0\\chromedriver\\chromedriver.exe"
	var port int = 9515

	//如果seleniumServer没有启动，就启动一个seleniumServer所需要的参数，可以为空，示例请参见https://github.com/tebeka/selenium/blob/master/example_test.go
	opts := []selenium.ServiceOption{}
	//opts := []selenium.ServiceOption{
	//    selenium.StartFrameBuffer(),           // Start an X frame buffer for the browser to run in.
	//    selenium.GeckoDriver(geckoDriverPath), // Specify the path to GeckoDriver in order to use Firefox.
	//}

	//selenium.SetDebug(true)
	service, err := selenium.NewChromeDriverService(seleniumPath, port, opts...)
	if nil != err {
		fmt.Println("start a chromedriver service falid", err.Error())
		return
	}
	//注意这里，server关闭之后，chrome窗口也会关闭
	defer service.Stop()

	//链接本地的浏览器 chrome
	caps := selenium.Capabilities{
		"browserName": "chrome",
	}

	//禁止图片加载，加快渲染速度
	imagCaps := map[string]interface{}{
		"profile.managed_default_content_settings.images": 2,
	}
	chromeCaps := chrome.Capabilities{
		Prefs: imagCaps,
		Path:  "",
		Args: []string{
			//"--headless", // 设置Chrome无头模式，在linux下运行，需要设置这个参数，否则会报错
			//"--no-sandbox",
			"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36", // 模拟user-agent，防反爬
		},
	}
	//以上是设置浏览器参数
	caps.AddChrome(chromeCaps)

	// 重新调起chrome浏览器
	w_b2, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
	if err != nil {
		fmt.Println("connect to the webDriver faild", err.Error())
		return
	}
	defer w_b2.Close()
	//打开一个网页
	err = w_b2.Get("https://www.toutiao.com/")
	if err != nil {
		fmt.Println("get page faild", err.Error())
		return
	}

	//w_b就是当前页面的对象，通过该对象可以操作当前页面了
	//........
	time.Sleep(5 * time.Minute)
	fmt.Println("seleniumGetUp exited ..")
}
